package com.vca.service.service.Impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vca.common.constants.CategoryConstants;
import com.vca.common.constants.Constants;
import com.vca.common.exception.VcaException;
import com.vca.common.model.category.Category;
import com.vca.common.model.course.Course;
import com.vca.common.model.course.CourseAbout;
import com.vca.common.model.exhibition.Exhibition;
import com.vca.common.model.system.SystemAttachment;
import com.vca.common.model.talk.Talk;
import com.vca.common.model.user.User;
import com.vca.common.model.user.UserCollection;
import com.vca.common.model.vca_product.VcaProduct;
import com.vca.common.model.vca_product.VcaProductAttr;
import com.vca.common.model.vca_product.VcaProductAttrValue;
import com.vca.common.model.vca_product.VcaProductInfo;
import com.vca.common.page.CommonPage;
import com.vca.common.request.*;
import com.vca.common.response.*;
import com.vca.common.utils.VcaUtil;
import com.vca.common.vo.PublicationInfoVo;
import com.vca.common.vo.VcaProductAttrValueVo;
import com.vca.service.dao.vca_product.VcaProductDao;
import com.vca.service.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author chenBing
 * @since 2022-11-16
 */
@Service
public class VcaProductServiceImpl extends ServiceImpl<VcaProductDao, VcaProduct> implements VcaProductService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private VcaProductInfoService vcaProductInfoService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserCollectionService userCollectionService;

    @Autowired
    private VcaProductAttrService vcaProductAttrService;

    @Autowired
    private VcaProductAttrValueService vcaProductAttrValueService;

    @Resource
    private VcaProductDao dao;

    @Autowired
    private UserService userService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private SystemGroupDataService systemGroupDataService;

    @Autowired
    private CourseAboutService courseAboutService;

    @Autowired
    private TalkService talkService;

    @Autowired
    private ExhibitionService exhibitionService;

    @Autowired
    private StoreCartService storeCartService;

    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;

    /**
     * @Description:出版物列表
     * @Author: chenBing
     * @Date: 2022/11/16
     */
    @Override
    public PageInfo<ShopsResponse> publicationListPage(PageParamRequest request) {
        Category category = categoryService.getById(Constants.CATEGORY_ID_OF_PUBLICATION_TYPE);
        Page<Object> objectPage = PageHelper.startPage(request.getPage(), request.getLimit());
        LambdaQueryWrapper<VcaProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(VcaProduct::getCid, category.getId());
        lqw.gt(VcaProduct::getStock, 0);
        lqw.eq(VcaProduct::getIsDeleted, 0);
        lqw.eq(VcaProduct::getIsShow, true);
        lqw.orderByDesc(VcaProduct::getSort);
        List<VcaProduct> vcaProductList = list(lqw);
        List<ShopsResponse> shopsResponses = new ArrayList<>();
        vcaProductList.forEach(vcaProduct -> {
            ShopsResponse shopsResponse = new ShopsResponse();
            shopsResponse.setId(vcaProduct.getId());
            shopsResponse.setName(vcaProduct.getName());
            shopsResponse.setPrice(vcaProduct.getPrice());
            shopsResponse.setCover(vcaProduct.getCoverImage());
            shopsResponse.setTypeLabelColor(category.getLabelColor());
            shopsResponse.setTypeName(category.getName());
            shopsResponse.setType(Constants.VCA_PRODUCT_TYPE_PUBLICATION);
            shopsResponses.add(shopsResponse);
        });
        return CommonPage.copyPageInfo(objectPage, shopsResponses);
    }

    /**
     *@Description:商品分页列表
     *@author:chenbing
     *@date 2023/1/31 17:40
     */
    @Override
    public PageInfo<ShopsResponse> shopListPage(String language,PageParamRequest request, Integer type) {
        List<ShopsResponse> shopList = new ArrayList<>();
        switch (type){
            //todo: 纪念品
            case 0:
                shopList = getShopList(language,Constants.CATEGORY_ID_OF_KEEPSAKE_TYPE,true);
                break;
            //todo: 出版物
            case 1:
                shopList = getShopList(language,Constants.CATEGORY_ID_OF_PUBLICATION_TYPE,true);
                break;
            //todo：礼品卡
            case 2:
                shopList = getShopList(language,Constants.CATEGORY_ID_OF_GIFT_CARD_TYPE,true);
                break;
            default:
                break;
        }
        return CommonPage.startPage(shopList,request.getPage(),request.getLimit());
    }

    /**
     * @Description:商品列表
     * @Author: chenBing
     * @Date: 2022/11/17
     */
    @Override
    public ShopListResponse shopList(String language) {
        ShopListResponse shopListResponse = new ShopListResponse();
        // TODO: 2022/11/17 礼品卡
        shopListResponse.setGiftcertificate(getShopList(language,Constants.CATEGORY_ID_OF_GIFT_CARD_TYPE,false));
        // TODO: 2022/11/17 纪念品
        shopListResponse.setSouvenir(getShopList(language,Constants.CATEGORY_ID_OF_KEEPSAKE_TYPE,false));
        // TODO: 2022/11/17 出版物 只查询两条数据
        shopListResponse.setPublication(getShopList(language,Constants.CATEGORY_ID_OF_PUBLICATION_TYPE,false));
        return shopListResponse;
    }

    /**
     * @Description:获得对应的商品集合
     * @Author: chenBing
     * @Date: 2022/11/17
     */
    public List<ShopsResponse> getShopList(String language,Integer shopType,Boolean isPage) {
        Category category = categoryService.getById(shopType);
        LambdaQueryWrapper<VcaProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(VcaProduct::getCid, category.getId());
//        lqw.gt(VcaProduct::getStock, 0);
        lqw.eq(VcaProduct::getIsDeleted, 0);
        lqw.eq(VcaProduct::getIsShow, true);
        lqw.orderByDesc(VcaProduct::getSort);
        if (!isPage){
            if (Objects.equals(shopType, Constants.CATEGORY_ID_OF_PUBLICATION_TYPE)) {
                lqw.last("LIMIT 0,2");
            }
            if (Objects.equals(shopType, Constants.CATEGORY_ID_OF_GIFT_CARD_TYPE) || Objects.equals(shopType,Constants.CATEGORY_ID_OF_KEEPSAKE_TYPE)) {
                lqw.last("LIMIT 0,5");
            }
        }
        List<VcaProduct> shopList = list(lqw);
        List<ShopsResponse> shopsResponses = new ArrayList<>();
        for (VcaProduct shop : shopList) {
            ShopsResponse shopsResponse = new ShopsResponse();
            shopsResponse.setId(shop.getId());
            if("en".equals(language)){
                shopsResponse.setName(shop.getNameEn());
                shopsResponse.setTypeName(category.getNameEn());
            }else{
                shopsResponse.setName(shop.getName());
                shopsResponse.setTypeName(category.getName());
            }
            shopsResponse.setPrice(shop.getPrice());
            shopsResponse.setCover(shop.getCoverImage());
            shopsResponse.setTypeLabelColor(category.getLabelColor());
            switch (shop.getCid()) {
                case 749:
                    shopsResponse.setType(Constants.VCA_PRODUCT_TYPE_SOUVENIR);
                    break;
                case 751:
                    shopsResponse.setType(Constants.VCA_PRODUCT_TYPE_PUBLICATION);
                    break;
                case 750:
                    shopsResponse.setType(Constants.VCA_PRODUCT_TYPE_GIFT_CARD);
                    break;
                default:
                    break;
            }
            shopsResponses.add(shopsResponse);
        }
        return shopsResponses;
    }

    /**
     * @param shopId 商品ID
     * @Description:商品详情
     * @Author: chenBing
     * @Date: 2022/11/17
     */
    @Override
    public ShopResponse shopInfo(String language,Integer shopId) {
        User user = userService.getInfo();
        ShopResponse shopResponse = new ShopResponse();
        VcaProduct shop = getById(shopId);
        if (shop == null) {
            if("en".equals(language)){
                throw new VcaException("The item does not exist");
            }else{
                throw new VcaException("该商品不存在");
            }
        }
        Category category = categoryService.getById(shop.getCid());
        shopResponse.setSharePoster(shop.getSharePoster());
        shopResponse.setStatus(shop.getIsShow());
        shopResponse.setIsDeleted(shop.getIsDeleted() ? 1 : 0);
        shopResponse.setShopId(shopId);
        if("en".equals(language)){
            shopResponse.setName(shop.getNameEn());
            shopResponse.setTypeName(category.getNameEn());
        }else{
            shopResponse.setName(shop.getName());
            shopResponse.setTypeName(category.getName());
        }
        shopResponse.setTypeLabelColor(category.getLabelColor());
        switch (shop.getCid()) {
            case 749:
                shopResponse.setType(Constants.VCA_PRODUCT_TYPE_SOUVENIR);
                break;
            case 751:
                shopResponse.setType(Constants.VCA_PRODUCT_TYPE_PUBLICATION);
                break;
            case 750:
                shopResponse.setType(Constants.VCA_PRODUCT_TYPE_GIFT_CARD);
                break;
            default:
                break;
        }
        if (user != null) {
            boolean collect = userCollectionService.count(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUid, user.getUid())
                    .eq(UserCollection::getMainType, Constants.ORDER_TYPE_PRODUCT).eq(UserCollection::getProductId, shop.getId())
                    .eq(UserCollection::getType, "collect").eq(UserCollection::getIsDeleted, false)) > 0;
            shopResponse.setIsCollection(collect);
        }

        if("en".equals(language)){
            shopResponse.setIntroduction(shop.getIntroductionEn());
        }else{
            shopResponse.setIntroduction(shop.getIntroduction());
        }
        shopResponse.setPrice(shop.getPrice());
        shopResponse.setCover(shop.getCoverImage());
        shopResponse.setAvailability(shop.getStock());
        shopResponse.setCarouselMap(JSONObject.parseArray(shop.getCarouselMap()));
        PublicationInfoVo publicationInfoVo = new PublicationInfoVo();
        VcaProductInfo publicationInfo = vcaProductInfoService.getOne(new LambdaQueryWrapper<VcaProductInfo>().eq(VcaProductInfo::getProductId, shopId));
        BeanUtils.copyProperties(publicationInfo, publicationInfoVo);

        if("en".equals(language)){
            publicationInfoVo.setDetails(JSONObject.parseArray(publicationInfo.getDetailsEn()));
        }else{
            publicationInfoVo.setDetails(JSONObject.parseArray(publicationInfo.getDetails()));
        }
        shopResponse.setTabInfo(publicationInfoVo);
        // TODO: 2022/9/23 处理相关课程推荐
        shopResponse.setEventRecommendations(courseService.getCourseAbouts(language,1, 4, Math.toIntExact(shopId)));
        // TODO: 2022/10/18 处理你可能喜欢的商品 推荐
        shopResponse.setShopRecommendations(courseService.getCourseAbouts(language,2, 4, Math.toIntExact(shopId)));
        // TODO: 2022/12/1 处理相关出版物推荐
        shopResponse.setPublicationRecommendations(courseService.getCourseAbouts(language,3, 4, Math.toIntExact(shopId)));
        // TODO: 2022/11/18 处理商品属性 获取商品规格
        List<VcaProductAttr> attrList = vcaProductAttrService.getListByProductIdAndType(shop.getId(), Constants.PRODUCT_TYPE_NORMAL);
        for (VcaProductAttr vcaProductAttr : attrList) {
            if(!language.isEmpty()){
                if("en".equals(language)){
                    vcaProductAttr.setAttrName(vcaProductAttr.getAttrNameEn());
                    vcaProductAttr.setAttrValues(vcaProductAttr.getAttrValuesEn());
                }
            }
        }
        //System.out.println(attrList+"-------------");
        shopResponse.setShopAttrs(attrList);
        // TODO: 2022/11/18 处理商品属性详情
        HashMap<String, Object> skuMap = new HashMap<>();
        List<VcaProductAttrValue> attrValueList = vcaProductAttrValueService.getListByProductIdAndType(shop.getId(), Constants.PRODUCT_TYPE_NORMAL);
        for (VcaProductAttrValue attrValue : attrValueList) {
            if(!language.isEmpty()){
                if("en".equals(language)){
                    attrValue.setAttrValue(attrValue.getAttrValueEn());
                    attrValue.setSuk(attrValue.getSukEn());
                }
            }

            VcaProductAttrValueVo vcaProductAttrValueVo = new VcaProductAttrValueVo();
            BeanUtils.copyProperties(attrValue, vcaProductAttrValueVo);
            skuMap.put(vcaProductAttrValueVo.getSuk(), vcaProductAttrValueVo);
        }

        //System.out.println(skuMap+"=========");
        shopResponse.setShopValue(skuMap);
        if (StringUtils.isNotBlank(shop.getMainPictureVideo())) {
            SystemAttachment systemAttachment = systemAttachmentService.getOne(new LambdaQueryWrapper<SystemAttachment>().eq(SystemAttachment::getSattDir, shop.getMainPictureVideo()));
            shopResponse.setMainPictureVideo(shop.getMainPictureVideo());
            shopResponse.setMainPictureVideoWidth(systemAttachment.getAttWidth());
            shopResponse.setMainPictureVideoHeight(systemAttachment.getAttHeight());
        }
        return shopResponse;
    }

    /**
     * 获取产品列表Admin
     *
     * @param request          筛选参数
     * @param pageParamRequest 分页参数
     * @return PageInfo
     */
    @Override
    public PageInfo<VcaProductResponse> getAdminList(StoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        //带 StoreProduct 类的多条件查询
        LambdaQueryWrapper<VcaProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //类型搜索
        if (ObjectUtil.isNotEmpty(request.getStatus())) {
            if (request.getStatus() == 1) {
                //出售中（已上架）
                lambdaQueryWrapper.eq(VcaProduct::getIsShow, true);
                lambdaQueryWrapper.eq(VcaProduct::getIsRecycle, false);
                lambdaQueryWrapper.eq(VcaProduct::getIsDeleted, false);
            } else {
                //仓库中（未上架）
                lambdaQueryWrapper.eq(VcaProduct::getIsShow, false);
                lambdaQueryWrapper.eq(VcaProduct::getIsRecycle, false);
                lambdaQueryWrapper.eq(VcaProduct::getIsDeleted, false);
            }
        }

        //关键字搜索
        if (StrUtil.isNotBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i
                    .or().eq(VcaProduct::getId, request.getKeywords())
                    .or().like(VcaProduct::getName, request.getKeywords())
                    .or().like(VcaProduct::getNameEn, request.getKeywords())
            );
        }
        if (ObjectUtil.isNotEmpty(request.getCateId())) {
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId, request.getCateId()).eq(Category::getIsDel, 0));
            if (category.getPid() == 0) {
                lambdaQueryWrapper.apply(StringUtils.isNotBlank(request.getCateId()), "FIND_IN_SET ('" + request.getCateId() + "', cid)");
            } else {
                lambdaQueryWrapper.apply(StringUtils.isNotBlank(request.getCateId()), "FIND_IN_SET ('" + request.getCateId() + "', child_cids)");
            }
        }
        lambdaQueryWrapper.orderByDesc(VcaProduct::getSort).orderByDesc(VcaProduct::getId);

        Page<VcaProduct> productPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<VcaProduct> products = dao.selectList(lambdaQueryWrapper);
        List<VcaProductResponse> productResponses = new ArrayList<>();
        for (VcaProduct product : products) {
            VcaProductResponse vcaProductResponse = new VcaProductResponse();
            BeanUtils.copyProperties(product, vcaProductResponse);
            vcaProductResponse.setFaceValue(ObjectUtil.isNotEmpty(product.getFaceValue()) ? product.getFaceValue().toString() : "0");
            VcaProductAttr attr = new VcaProductAttr();
            attr.setProductId(product.getId());
            List<VcaProductAttr> attrs = vcaProductAttrService.getByEntity(attr);

            if (attrs.size() > 0) {
                vcaProductResponse.setAttr(attrs);
            }
            List<VcaProductAttrValueResponse> vcaProductAttrValueResponses = new ArrayList<>();

            VcaProductAttr vcaProductAttr = new VcaProductAttr();
            vcaProductAttr.setProductId(product.getId());
            List<VcaProductAttr> vcaProductAttrs = vcaProductAttrService.getByEntity(vcaProductAttr);
            vcaProductAttrs.stream().map(e -> {
                VcaProductAttrValueResponse response = new VcaProductAttrValueResponse();
                BeanUtils.copyProperties(e, response);
                vcaProductAttrValueResponses.add(response);
                return e;
            }).collect(Collectors.toList());
            vcaProductResponse.setAttrValue(vcaProductAttrValueResponses);
            // 处理富文本
            VcaProductInfo productInfo = vcaProductInfoService.getOne(new LambdaQueryWrapper<VcaProductInfo>()
                    .eq(VcaProductInfo::getProductId, product.getId()));
            if (ObjectUtil.isNotEmpty(productInfo)) {
                vcaProductResponse.setContent(null == productInfo.getDetails() ? "" : productInfo.getDetails());
            }

            vcaProductResponse.setCollectCount(
                    userCollectionService.getAdminList(product.getId(), 4).size());
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId, product.getCid()).eq(Category::getType, 1));
            vcaProductResponse.setCategoryName("");
            if (ObjectUtil.isNotEmpty(category)) {
                vcaProductResponse.setCategoryName(category.getName());
                vcaProductResponse.setCourseType(category.getName());
            }

            productResponses.add(vcaProductResponse);
        }
        // 多条sql查询处理分页正确
        return CommonPage.copyPageInfo(productPage, productResponses);
    }

    /**
     * @Description:获取购物车商品信息
     * @Author: chenBing
     * @Date: 2022/11/21
     */
    @Override
    public VcaProduct getCartByProId(Integer productId) {
        LambdaQueryWrapper<VcaProduct> lqw = Wrappers.lambdaQuery();
        lqw.select(VcaProduct::getId, VcaProduct::getCid, VcaProduct::getImage, VcaProduct::getName, VcaProduct::getNameEn);
        lqw.eq(VcaProduct::getId, productId);
        return dao.selectOne(lqw);
    }

    /**
     * 修改商品排序
     *
     * @param productId
     * @param sort
     * @return
     * @author Li
     * @date 2022/11/23 10:05
     */
    @Override
    public boolean updateSort(Integer productId, Integer sort) {
        VcaProduct product = getProduct(productId);
        product.setSort(sort);
        return transactionTemplate.execute(e -> {
            dao.updateById(product);
            return Boolean.TRUE;
        });
    }

    /**
     * 新增商品
     *
     * @param request 商品请求对象
     * @return Boolean
     */
    @Override
    public Boolean addProduct(VcaProductAddRequest request) {

        //校验添加的相关课程是否存在
        if (ObjectUtil.isNotEmpty(request.getCourseAboutAddRequests())) {
            Map<Integer, List<CourseAboutAddRequest>> listMap = request.getCourseAboutAddRequests().stream().collect(Collectors.groupingBy(e -> e.getTypeCourse()));
            courseAboutService.checkWhetherCourseAbout(listMap);
        }

        if (ObjectUtil.isEmpty(request.getCid())) {
            throw new VcaException("商品分类不可为空");
        }

        VcaProduct vcaProduct = new VcaProduct();
        BeanUtils.copyProperties(request, vcaProduct);
        vcaProduct.setMainColor(null);
        vcaProduct.setTertiaryColor(null);
        vcaProduct.setSecondaryColor(null);
        vcaProduct.setIsShow(false);

        //主图
        vcaProduct.setImage(systemAttachmentService.clearPrefix(vcaProduct.getImage()));
        List<String> carouselMap = new ArrayList();
        request.getCarouselMap().forEach(e -> {
            carouselMap.add(systemAttachmentService.clearPrefix(e));
        });
        //轮播图
        vcaProduct.setCarouselMap(JSONObject.toJSONString(carouselMap));
        // systemAttachmentService.clearPrefix(vcaProduct.getFlatPattern())
        vcaProduct.setCoverImage(systemAttachmentService.clearPrefix(request.getCoverImage()));
        //分享海报
        vcaProduct.setSharePoster(systemAttachmentService.clearPrefix(request.getSharePoster()));
        if (ObjectUtil.isNotEmpty(request.getMainPictureVideo())) {
            vcaProduct.setMainPictureVideo(systemAttachmentService.clearPrefix(request.getMainPictureVideo()));
        }

        Map<String, List> cardList = systemGroupDataService.getCardList();
        List card = cardList.get("cardList");
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<Category>();
        wrapper.eq(Category::getStatus, 1);
        wrapper.eq(Category::getIsDel, 0);
        Category category = categoryService.getOne(wrapper.eq(Category::getId, request.getCid()));
        if (ObjectUtil.isEmpty(category)) {
            throw new VcaException("该商品类型不存在");
        }

        if (category.getId().equals(CategoryConstants.CATEGORY_TYPE_GIFTCARD)) {

            vcaProduct.setEndTime(request.getEndTime());
            vcaProduct.setCardNo(request.getCardNo());
            vcaProduct.setMainColor(request.getMainColor());
            vcaProduct.setSecondaryColor(request.getSecondaryColor());
            vcaProduct.setTertiaryColor(request.getTertiaryColor());
            vcaProduct.setFaceValue(new BigDecimal(request.getFaceValue()));

            if (ObjectUtil.isNotEmpty(request.getPrimaryKeys())) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Integer i : request.getPrimaryKeys()) {
                    if (ObjectUtil.isEmpty(stringBuilder)) {
                        stringBuilder.append(i);
                    } else {
                        stringBuilder.append("," + i);
                    }
                }
                vcaProduct.setPrimaryKey(stringBuilder.toString());
            }
            vcaProduct.setUseType(request.getUseType());
        }
        if (category.getId().equals(CategoryConstants.CATEGORY_TYPE_PUBLICATION)) {
            vcaProduct.setIsbnCode(request.getAttrValue().get(0).getIsbnCode());
        }

        if (ObjectUtil.isNotEmpty(request.getChildren())) {
            List<Category> childList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, request.getChildren()).eq(Category::getStatus, 1).eq(Category::getIsDel, 0));
            if (childList.size() < request.getChildren().size()) {
                throw new VcaException("选择的子类不存在,请重新刷新页面");
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (Integer i : request.getChildren()) {
                if (ObjectUtil.isEmpty(stringBuilder)) {
                    stringBuilder.append(i);
                } else {
                    stringBuilder.append("," + i);
                }
            }
            vcaProduct.setChildCids(stringBuilder.toString());
        }

        // 多规格需要校验规格参数
        if (!request.getSpecType()) {
            if (request.getAttrValue().size() > 1) {
                throw new VcaException("单规格商品属性值不能大于1");
            }
        }


        List<StoreProductAttrValueAddRequest> attrValueAddRequestList = request.getAttrValue();
        System.out.println(attrValueAddRequestList+"@@@@@@@@@@@");
        //计算价格
        StoreProductAttrValueAddRequest minAttrValue = attrValueAddRequestList.stream().min(Comparator.comparing(StoreProductAttrValueAddRequest::getPrice)).get();
        vcaProduct.setPrice(minAttrValue.getPrice());
        vcaProduct.setStock(attrValueAddRequestList.stream().mapToInt(StoreProductAttrValueAddRequest::getStock).sum());

        vcaProduct.setIsShow(false);
        // 默认值设置
        if (ObjectUtil.isNull(request.getSort())) {
            vcaProduct.setSort(0);
        }

        List<StoreProductAttrAddRequest> addRequestList = request.getAttr();

        List<VcaProductAttr> attrList = addRequestList.stream().map(e -> {
            VcaProductAttr attr = new VcaProductAttr();
            BeanUtils.copyProperties(e, attr);
            attr.setType(false);

            return attr;
        }).collect(Collectors.toList());
        System.out.println(attrList+"========");

        List<VcaProductAttrValue> attrValueList = attrValueAddRequestList.stream().map(e -> {
            VcaProductAttrValue attrValue = new VcaProductAttrValue();
            BeanUtils.copyProperties(e, attrValue);
            attrValue.setSuk(getSku(e.getAttrValue()));
            attrValue.setSukEn(getSku(e.getAttrValueEn()));

            attrValue.setAttrValue(e.getAttrValue());
            attrValue.setAttrValueEn(e.getAttrValueEn());

            attrValue.setSales(0);
            attrValue.setType(Constants.PRODUCT_TYPE_NORMAL);
            attrValue.setImage(systemAttachmentService.clearPrefix(e.getImage()));
            return attrValue;
        }).collect(Collectors.toList());
        System.out.println(attrValueList+"---------");

        // 商品详情
        VcaProductInfo productInfo = new VcaProductInfo();
        productInfo.setDetails(systemAttachmentService.clearPrefix(request.getDetails()));
        productInfo.setDetailsEn(systemAttachmentService.clearPrefix(request.getDetailsEn()));

        List<CourseAbout> courseAboutList = new ArrayList<>();

        return transactionTemplate.execute(e -> {
            save(vcaProduct);

            //添加套课和相关课程或商品的关系
            request.getCourseAboutAddRequests().forEach(g -> {
                CourseAbout courseAbout = new CourseAbout();
                BeanUtils.copyProperties(g, courseAbout);
                if (ObjectUtil.isEmpty(g.getSort())) {
                    courseAbout.setSort(0);
                }
                courseAbout.setTypeMainCourse(4);
                courseAbout.setAboutMainId(vcaProduct.getId().longValue());
                courseAboutList.add(courseAbout);
            });
            courseAboutService.addCourseAboutList(courseAboutList);

            attrList.forEach(attr -> attr.setProductId(vcaProduct.getId()));
            attrValueList.forEach(value -> value.setProductId(vcaProduct.getId()));
            vcaProductAttrService.saveBatch(attrList);
            vcaProductAttrValueService.saveBatch(attrValueList);

            productInfo.setProductId(vcaProduct.getId());
            //添加商品详情
            vcaProductInfoService.save(productInfo);

            return Boolean.TRUE;
        });
    }

    /**
     * 获得商品头部数据
     *
     * @return
     * @author Li
     * @date 2022/11/23 09:16
     */
    @Override
    public List<AdminHeaderResponse> getHeader() {
        List<AdminHeaderResponse> headers = new ArrayList();
        AdminHeaderResponse active = new AdminHeaderResponse(0, "Active", 1, null);
        AdminHeaderResponse inActive = new AdminHeaderResponse(0, "InActive", 0, null);
        active.setCount(dao.selectList(new LambdaQueryWrapper<VcaProduct>().eq(VcaProduct::getIsShow, 1).eq(VcaProduct::getIsDeleted, 0)).size());
        inActive.setCount(dao.selectList(new LambdaQueryWrapper<VcaProduct>().eq(VcaProduct::getIsShow, 0).eq(VcaProduct::getIsDeleted, 0)).size());
        headers.add(active);
        headers.add(inActive);
        return headers;
    }

    /**
     * 根据商品id获取商品信息
     *
     * @param productId
     * @return
     * @author Li
     * @date 2022/11/24 09:54
     */
    @Override
    public ProductAdminResponse getProductAdmin(Integer productId) {
        ProductAdminResponse response = new ProductAdminResponse();
        VcaProduct vcaProduct = getProduct(productId);
        BeanUtils.copyProperties(vcaProduct, response);
        VcaProductInfo productInfo = vcaProductInfoService.getOne(new LambdaQueryWrapper<VcaProductInfo>().eq(VcaProductInfo::getProductId, productId));
        response.setDetails(productInfo.getDetails());
        response.setDetailsEn(productInfo.getDetailsEn());
        response.setFaceValue(ObjectUtil.isNotEmpty(vcaProduct.getFaceValue()) ? vcaProduct.getFaceValue().toString() : "0");
        if (ObjectUtil.isNotEmpty(vcaProduct.getPrimaryKey())) {
            List<Integer> primaryKeys = VcaUtil.stringToArray(vcaProduct.getPrimaryKey());
            response.setPrimaryKeys(primaryKeys);
        }

        List<VcaProductAttr> attrList = vcaProductAttrService.getListByProductIdAndType(vcaProduct.getId(), Constants.PRODUCT_TYPE_NORMAL);
        response.setAttr(attrList);

        List<VcaProductAttrValue> attrValueList = vcaProductAttrValueService.getListByProductIdAndType(vcaProduct.getId(), Constants.PRODUCT_TYPE_NORMAL);
        System.out.println(attrValueList+"!!!!!!!!");
        List<AttrValueResponse> valueResponseList = attrValueList.stream().map(e -> {
            AttrValueResponse valueResponse = new AttrValueResponse();
            BeanUtils.copyProperties(e, valueResponse);
            valueResponse.setAttrValue(e.getAttrValue());
            valueResponse.setAttrValueEn(e.getAttrValueEn());
            return valueResponse;
        }).collect(Collectors.toList());
        System.out.println(valueResponseList+"--------");
        response.setAttrValue(valueResponseList);

        List<CourseAbout> courseAbouts = courseAboutService.list(new LambdaQueryWrapper<CourseAbout>().eq(CourseAbout::getAboutMainId, productId).eq(CourseAbout::getIsDeleted, 0).eq(CourseAbout::getTypeMainCourse, 4));
        //将相关课程和商品根据0 = 课程 1=讲座 2=展览 3=商品 4=套课
        Map<Integer, List<CourseAbout>> listMap = courseAbouts.stream().collect(Collectors.groupingBy(e -> e.getTypeCourse()));

        Map<String, List<HashMap<String, Object>>> courseAdminConfig = systemGroupDataService.getCourseAdminConfig();
        List<CourseAboutAdminResponse> aboutList = courseAboutService.getAdminCourseAbout(listMap, courseAdminConfig);
        response.setCourseAboutAdminResponses(aboutList);
        if (ObjectUtil.isNotEmpty(vcaProduct.getChildCids())) {
            response.setChildren(VcaUtil.stringToArray(vcaProduct.getChildCids()));
        }

        List<ProductAdminResponse.CourseList> courseLists = new ArrayList<>();
        if (response.getUseType() == 2) {
            switch (response.getUseAround()) {
                case 0:
                    response.getPrimaryKeys().forEach(e -> {
                        Course course = courseService.getOne(new LambdaQueryWrapper<Course>().eq(Course::getId, e).eq(Course::getIsDeleted, 0));
                        if (ObjectUtil.isNotEmpty(course)) {
                            ProductAdminResponse.CourseList courseList = new ProductAdminResponse.CourseList();
                            courseList.setId(course.getId());
                            courseList.setCoverImage(course.getCover());
                            courseLists.add(courseList);
                        }
                    });
                    break;
                case 1:
                    response.getPrimaryKeys().forEach(e -> {
                        Talk talk = talkService.getOne(new LambdaQueryWrapper<Talk>().eq(Talk::getId, e).eq(Talk::getIsDeleted, 0));
                        if (ObjectUtil.isNotEmpty(talk)) {
                            ProductAdminResponse.CourseList courseList = new ProductAdminResponse.CourseList();
                            courseList.setId(talk.getId());
                            courseList.setCoverImage(talk.getCoverImage());
                            courseLists.add(courseList);
                        }
                    });
                    break;
                case 2:
                    response.getPrimaryKeys().forEach(e -> {
                        Exhibition exhibition = exhibitionService.getOne(new LambdaQueryWrapper<Exhibition>().eq(Exhibition::getId, e).eq(Exhibition::getIsDeleted, 0));
                        if (ObjectUtil.isNotEmpty(exhibition)) {
                            ProductAdminResponse.CourseList courseList = new ProductAdminResponse.CourseList();
                            courseList.setId(exhibition.getId());
                            courseList.setCoverImage(exhibition.getCover());
                            courseLists.add(courseList);
                        }
                    });
                    break;
                default:
                    break;
            }
        }
        response.setCourseList(courseLists);
        return response;
    }

    /**
     * 上架
     *
     * @param id
     */
    @Override
    public boolean putOnShelf(Integer id) {
        VcaProduct product = getProduct(id);
        if (product.getIsShow()) {
            return true;
        }

        // 获取商品skuid
        VcaProductAttrValue tempSku = new VcaProductAttrValue();
        tempSku.setProductId(id);
        tempSku.setType(Constants.PRODUCT_TYPE_NORMAL);
        vcaProductAttrValueService.getByEntity(tempSku);

        List<VcaProductAttrValue> skuList = vcaProductAttrValueService.getByEntity(tempSku);
        List<Integer> skuIdList = skuList.stream().map(VcaProductAttrValue::getId).collect(Collectors.toList());

        product.setIsShow(true);
        Boolean execute = transactionTemplate.execute(e -> {
            dao.updateById(product);
            storeCartService.productStatusNoEnable(skuIdList);
            return Boolean.TRUE;
        });
        return execute;
    }

    /**
     * 下架
     *
     * @param id
     */
    @Override
    public boolean offShelf(Integer id) {
        VcaProduct product = getProduct(id);
        if (!product.getIsShow()) {
            return true;
        }

        product.setIsShow(false);
        Boolean execute = transactionTemplate.execute(e -> {
            dao.updateById(product);
            storeCartService.productStatusNotEnable(id);
            return Boolean.TRUE;
        });

        return execute;
    }

    /**
     * 商品修改
     *
     * @param request 商品参数
     */
    @Override
    public boolean updatePrdouct(VcaProductAddRequest request) {
        //校验添加的相关课程是否存在
        Map<Integer, List<CourseAboutAddRequest>> listMap = request.getCourseAboutAddRequests().stream().collect(Collectors.groupingBy(e -> e.getTypeCourse()));
        courseAboutService.checkWhetherCourseAbout(listMap);

        if (ObjectUtil.isEmpty(request.getCid())) {
            throw new VcaException("商品分类不可为空");
        }

        VcaProduct vcaProduct = getProduct(request.getId());
        BeanUtils.copyProperties(request, vcaProduct);
        vcaProduct.setMainColor(null);
        vcaProduct.setTertiaryColor(null);
        vcaProduct.setSecondaryColor(null);
        vcaProduct.setIsShow(false);

        //主图
        vcaProduct.setImage(systemAttachmentService.clearPrefix(vcaProduct.getImage()));
        List<String> carouselMap = new ArrayList();
        request.getCarouselMap().forEach(e -> {
            carouselMap.add(systemAttachmentService.clearPrefix(e));
        });
        //轮播图
        vcaProduct.setCarouselMap(JSONObject.toJSONString(carouselMap));
        vcaProduct.setCoverImage(systemAttachmentService.clearPrefix(request.getCoverImage()));
        //分享海报
        vcaProduct.setSharePoster(systemAttachmentService.clearPrefix(request.getSharePoster()));
        if (ObjectUtil.isNotEmpty(request.getMainPictureVideo())) {
            vcaProduct.setMainPictureVideo(systemAttachmentService.clearPrefix(request.getMainPictureVideo()));
        }

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<Category>();
        wrapper.eq(Category::getStatus, 1);
        wrapper.eq(Category::getIsDel, 0);
        Category category = categoryService.getOne(wrapper.eq(Category::getId, request.getCid()));
        if (ObjectUtil.isEmpty(category)) {
            throw new VcaException("该商品类型不存在");
        }

        if (category.getId().equals(CategoryConstants.CATEGORY_TYPE_GIFTCARD)) {
            vcaProduct.setCardNo(request.getCardNo());
            vcaProduct.setEndTime(request.getEndTime());
            vcaProduct.setMainColor(request.getMainColor());
            vcaProduct.setSecondaryColor(request.getSecondaryColor());
            vcaProduct.setTertiaryColor(request.getTertiaryColor());
            vcaProduct.setFaceValue(new BigDecimal(request.getFaceValue()));

            vcaProduct.setPrimaryKey(null);
            if (ObjectUtil.isNotEmpty(request.getPrimaryKeys())) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Integer i : request.getPrimaryKeys()) {
                    if (ObjectUtil.isEmpty(stringBuilder)) {
                        stringBuilder.append(i);
                    } else {
                        stringBuilder.append("," + i);
                    }
                }
                vcaProduct.setPrimaryKey(stringBuilder.toString());
            }

            vcaProduct.setUseType(request.getUseType());
        }
        if (category.getId().equals(CategoryConstants.CATEGORY_TYPE_PUBLICATION)) {
            vcaProduct.setIsbnCode(request.getIsbnCode());
        }

        if (ObjectUtil.isNotEmpty(request.getChildren())) {
            List<Category> childList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, request.getChildren()).eq(Category::getStatus, 1).eq(Category::getIsDel, 0));
            if (childList.size() < request.getChildren().size()) {
                throw new VcaException("选择的子类不存在,请重新刷新页面");
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (Integer i : request.getChildren()) {
                if (ObjectUtil.isEmpty(stringBuilder)) {
                    stringBuilder.append(i);
                } else {
                    stringBuilder.append("," + i);
                }
            }
            vcaProduct.setChildCids(stringBuilder.toString());
        }
        // 多规格需要校验规格参数
        if (!request.getSpecType()) {
            if (request.getAttrValue().size() > 1) {
                throw new VcaException("单规格商品属性值不能大于1");
            }
        }


        List<StoreProductAttrValueAddRequest> attrValueAddRequestList = request.getAttrValue();
        //计算价格
        StoreProductAttrValueAddRequest minAttrValue = attrValueAddRequestList.stream().min(Comparator.comparing(StoreProductAttrValueAddRequest::getPrice)).get();
        vcaProduct.setPrice(minAttrValue.getPrice());
        vcaProduct.setStock(attrValueAddRequestList.stream().mapToInt(StoreProductAttrValueAddRequest::getStock).sum());

        vcaProduct.setIsShow(false);
        // 默认值设置
        if (ObjectUtil.isNull(request.getSort())) {
            vcaProduct.setSort(0);
        }

        // attr部分
        List<StoreProductAttrAddRequest> addRequestList = request.getAttr();
        List<VcaProductAttr> attrAddList = CollUtil.newArrayList();
        List<VcaProductAttr> attrUpdateList = CollUtil.newArrayList();
        addRequestList.forEach(e -> {
            VcaProductAttr attr = new VcaProductAttr();
            BeanUtils.copyProperties(e, attr);
            if (ObjectUtil.isNull(attr.getId())) {
                attr.setProductId(vcaProduct.getId());
                attr.setType(false);
                attrAddList.add(attr);
            } else {
                attr.setIsDeleted(false);
                attrUpdateList.add(attr);
            }
        });

        // attrValue部分
        List<VcaProductAttrValue> attrValueAddList = CollUtil.newArrayList();
        List<VcaProductAttrValue> attrValueUpdateList = CollUtil.newArrayList();
        attrValueAddRequestList.forEach(e -> {
            VcaProductAttrValue attrValue = new VcaProductAttrValue();
            BeanUtils.copyProperties(e, attrValue);
            attrValue.setSuk(getSku(e.getAttrValue()));
            attrValue.setImage(systemAttachmentService.clearPrefix(e.getImage()));
            attrValue.setAttrValue(e.getAttrValue());
            if (ObjectUtil.isNull(attrValue.getId()) || attrValue.getId().equals(0)) {
                attrValue.setId(null);
                attrValue.setProductId(vcaProduct.getId());
                attrValue.setType(Constants.PRODUCT_TYPE_NORMAL);
                attrValueAddList.add(attrValue);
            } else {
                attrValue.setIsDeleted(false);
                attrValueUpdateList.add(attrValue);
            }
        });


        // 商品详情
        VcaProductInfo productInfo = vcaProductInfoService.getOne(new LambdaQueryWrapper<VcaProductInfo>().eq(VcaProductInfo::getProductId, request.getId()));
        productInfo.setDetails(systemAttachmentService.clearPrefix(request.getDetails()));
        productInfo.setDetailsEn(systemAttachmentService.clearPrefix(request.getDetailsEn()));
        List<CourseAbout> courseAboutList = new ArrayList<>();

        //添加套课和相关课程或商品的关系
        request.getCourseAboutAddRequests().forEach(g -> {
            CourseAbout courseAbout = new CourseAbout();
            BeanUtils.copyProperties(g, courseAbout);
            if (ObjectUtil.isEmpty(g.getSort())) {
                courseAbout.setSort(0);
            }
            courseAbout.setTypeMainCourse(4);
            courseAbout.setAboutMainId(vcaProduct.getId().longValue());
            if (ObjectUtil.isNotEmpty(g.getCourseAboutId())) {
                courseAbout.setId(g.getCourseAboutId());
            }
            courseAboutList.add(courseAbout);
        });
        return transactionTemplate.execute(e -> {
            updateById(vcaProduct);

            //修改套课和相关课程或商品的关系
            courseAboutService.updateCourseAboutList(courseAboutList, request.getId().longValue());

            // 先删除原用attr+value
            vcaProductAttrService.deleteByProductIdAndType(vcaProduct.getId(), Constants.PRODUCT_TYPE_NORMAL);
            vcaProductAttrValueService.deleteByProductIdAndType(vcaProduct.getId(), Constants.PRODUCT_TYPE_NORMAL);

            if (CollUtil.isNotEmpty(attrAddList)) {
                vcaProductAttrService.saveBatch(attrAddList);
            }
            if (CollUtil.isNotEmpty(attrUpdateList)) {
                vcaProductAttrService.saveOrUpdateBatch(attrUpdateList);
            }

            if (CollUtil.isNotEmpty(attrValueAddList)) {
                vcaProductAttrValueService.saveBatch(attrValueAddList);
            }
            if (CollUtil.isNotEmpty(attrValueUpdateList)) {
                vcaProductAttrValueService.saveOrUpdateBatch(attrValueUpdateList);
            }
            //添加商品详情
            vcaProductInfoService.updateById(productInfo);

            return Boolean.TRUE;
        });
    }

    /**
     * 删除商品
     *
     * @param id Integer
     */
    @Override
    public boolean deleteProduct(Integer id) {
        VcaProduct product = getProduct(id);
        product.setIsDeleted(true);
        List<CourseAbout> abouts = courseAboutService.list(new LambdaQueryWrapper<CourseAbout>().eq(CourseAbout::getAboutMainId, id).eq(CourseAbout::getIsDeleted, 0));
        return transactionTemplate.execute(e -> {
            courseAboutService.delByids(abouts.stream().map(CourseAbout::getId).collect(Collectors.toList()));
            storeCartService.productStatusNotEnable(id);
            dao.update(product, new LambdaUpdateWrapper<VcaProduct>().eq(VcaProduct::getId, id).set(VcaProduct::getIsDeleted, 1));
            return Boolean.TRUE;
        });
    }

    @Override
    public List<VcaProduct> getProductsAndDelete(List<Integer> ids) {
        return dao.getProducts(ids);
    }

    /**
     * 查询商品是否存在
     *
     * @param productId
     * @return
     */
    private VcaProduct getProduct(Integer productId) {
        LambdaQueryWrapper<VcaProduct> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(VcaProduct::getId, productId);
        wrapper.eq(VcaProduct::getIsDeleted, 0);
        VcaProduct product = dao.selectOne(wrapper);
        if (ObjectUtil.isEmpty(product)) {
            throw new VcaException("该商品不存在");
        }
        return product;
    }

    /**
     * 商品sku
     *
     * @param attrValue json字符串
     * @return sku
     */
    private String getSku(String attrValue) {
        LinkedHashMap<String, String> linkedHashMap = JSONObject.parseObject(attrValue, LinkedHashMap.class, Feature.OrderedField);
        Iterator<Map.Entry<String, String>> iterator = linkedHashMap.entrySet().iterator();
        List<String> strings = CollUtil.newArrayList();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            strings.add(next.getValue());
        }
//        List<String> strings = jsonObject.values().stream().map(o -> (String) o).collect(Collectors.toList());
        return String.join(",", strings);
    }


}
